package com.heer.gymnasium.module.my.views;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.TextView;

import com.heer.amap.utils.ToastUtil;
import com.heer.gymnasium.R;
import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.api.callback.BaseCallback;
import com.heer.gymnasium.base.BaseActivity;
import com.heer.gymnasium.module.login.views.LoginActivity;
import com.heer.gymnasium.module.my.beans.UserBean;
import com.heer.gymnasium.util.Base64Util;
import com.heer.gymnasium.util.ImageUtil;
import com.heer.gymnasium.util.StringUtils;
import com.zhihuiyun.library.utils.BitmapUtils;
import com.zhihuiyun.library.view.CircleImageView;

import java.io.FileNotFoundException;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by yan on 2018/1/18.
 * 个人资料界面
 */

public class MyInfoActivity extends BaseActivity {
    private static final int RES_ID_HEAD = R.id.layout_myinfo_head_iv;
    private static final int RES_ID_HEAD_PANEL = R.id.layout_myinfo_head_rl;
    private static final int RES_ID_USERNAME = R.id.layout_myinfo_username_tv;
    private static final int RES_ID_IPHONE = R.id.layout_myinfo_iphone_tv;
    private static final int RES_ID_SEX = R.id.layout_myinfo_sex_tv;
    private static final int RES_ID_BIRTHDAY = R.id.layout_myinfo_birthday_tv;
    private static final int RES_ID_BIRTHDAY_PANEL = R.id.layout_myinfo_birthday_rl;
    private static final int RES_ID_NAME_PANEL = R.id.layout_myinfo_username_rl;
    private static final int RES_ID_SEX_PANEL = R.id.layout_myinfo_sex_rl;
    private static final int RES_ID_HEIGHT = R.id.layout_myinfo_height_tv;
    private static final int RES_ID_HEIGHT_RL = R.id.layout_myinfo_height_rl;
    private static final int RES_ID_WEIGHT = R.id.layout_myinfo_weight_tv;
    private static final int RES_ID_WEIGHT_RL = R.id.layout_myinfo_weight_rl;
    private static final int RES_ID_LABEL_PANEL = R.id.layout_myinfo_label_rl;

    @BindView(RES_ID_IPHONE)
    TextView iphoneTextVew;
    @BindView(RES_ID_HEIGHT)
    TextView heightTextVew;
    @BindView(RES_ID_WEIGHT)
    TextView weightTextVew;
    @BindView(RES_ID_USERNAME)
    TextView nameTextView;
    @BindView(RES_ID_SEX)
    TextView sexTextView;
    @BindView(RES_ID_BIRTHDAY)
    TextView birthdayTextView;
    @BindView(RES_ID_HEAD)
    CircleImageView headImageView;

    private MyInfoActivity $this;
    private UserBean bean;

    /**
     * TODO 界面跳转，传参需定义
     *
     * @param context
     */
    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MyInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init() {
        super.init();
        $this = this;
        setContentView(R.layout.layout_myinfo);
    }

    @Override
    protected void initView() {
        super.initView();
        titleUtils.setTitleText("我的资料");
    }

    @Override
    protected void loadData() {
        super.loadData();
        getUserinfo();
    }

    final int REQUEST_CODE_CONTACT = 101;
    private static final int REQUEST_CODE_PICK_IMAGE = 2;

    @OnClick({RES_ID_IPHONE, RES_ID_HEIGHT_RL, RES_ID_WEIGHT_RL, RES_ID_LABEL_PANEL, RES_ID_BIRTHDAY_PANEL, RES_ID_HEAD_PANEL, RES_ID_SEX_PANEL, RES_ID_NAME_PANEL})
    public void onClick(View view) {
        switch (view.getId()) {
            case RES_ID_IPHONE:
                InfoSetActivity.startActivityForResult(this, InfoSetActivity.IInfoConstants.PHONE);
                break;
            case RES_ID_HEIGHT_RL:
                InfoSetActivity.startActivityForResult(this, InfoSetActivity.IInfoConstants.HEIGHT);
                break;
            case RES_ID_WEIGHT_RL:
                InfoSetActivity.startActivityForResult(this, InfoSetActivity.IInfoConstants.WEIGHT);
                break;
            case RES_ID_LABEL_PANEL:
                MyLabelActivity.startActivity(this, bean);
                break;
            case RES_ID_BIRTHDAY_PANEL:
                InfoSetActivity.startActivityForResult(this, InfoSetActivity.IInfoConstants.BIRTHDAY);
                break;
            case RES_ID_HEAD_PANEL:
                boolean hasPermission = true;
                if (Build.VERSION.SDK_INT >= 23) {
                    String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE};
                    //验证是否许可权限
                    for (String str : permissions) {
                        if (this.checkSelfPermission(str) != PackageManager.PERMISSION_GRANTED) {
                            //申请权限
                            this.requestPermissions(permissions, REQUEST_CODE_CONTACT);
                            hasPermission = false;
                        }
                    }
                }
                if (hasPermission) {
                    toGallery();
                }
                break;
            case RES_ID_SEX_PANEL:
                InfoSetActivity.startActivityForResult(this, InfoSetActivity.IInfoConstants.SEX);
                break;
            case RES_ID_NAME_PANEL:
                InfoSetActivity.startActivityForResult(this, InfoSetActivity.IInfoConstants.NICKNAME);
                break;
        }
    }

    private void toGallery() {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");//相片类型
        startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_CONTACT) {
            toGallery();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_PICK_IMAGE && RESULT_OK == resultCode) {
            if (data == null) {
                ToastUtil.show($this, "图片有点问题");
                return;
            }

            Uri uri = data.getData();

            try {
                Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                mAppHelper.apiService().setUserImg(Base64Util.bitmapToBase64(bitmap)).enqueue(new BaseCallback<ApiResponse<Object>>() {
                    @Override
                    public void onSuccess(Call<ApiResponse<Object>> call, Response<ApiResponse<Object>> response) {
                        getUserinfo();
                    }
                });
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                ToastUtil.show($this, "读取文件失败");
            }
        } else {
            getUserinfo();
        }
    }


    /**
     * 获取用户信息
     */
    public void getUserinfo() {
        SignHelper signHelper = new SignHelper("");
        mAppHelper.apiService().getuserInfo(signHelper.getToken()).enqueue(new BaseCallback<ApiResponse<UserBean>>() {
            @Override
            public void onSuccess(Call<ApiResponse<UserBean>> call, Response<ApiResponse<UserBean>> response) {
                if (response.isSuccessful() && response.body().isSccessful()) {
                    bean = response.body().getData();
                    if (bean != null) {
                        nameTextView.setText(bean.getNickname());
                        if (bean.getSex().equals("1")) {
                            sexTextView.setText("男");
                        } else if (bean.getSex().equals("2")) {
                            sexTextView.setText("女");
                        } else {
                            sexTextView.setText("未知");
                        }
                        if ("0".equals(bean.getPhone())) {
                            iphoneTextVew.setText("您还未绑定手机号");
                        } else {
                            iphoneTextVew.setText(bean.getPhone());
                            iphoneTextVew.setOnClickListener(null);
                            iphoneTextVew.setCompoundDrawables(null, null, null, null);
                        }
                        if ("0".equals(bean.getPhone())) {
                            birthdayTextView.setText("您还设置生日");
                        } else {
                            String birthday = StringUtils.timeStamp10ToDate(String.valueOf(bean.getBirthday()), StringUtils.DATE_FORMAT_TO_MONTH);
                            birthdayTextView.setText(birthday);
                        }

                        if ("0".equals(bean.getHeight())) {
                            heightTextVew.setText("未设置");
                        } else {
                            heightTextVew.setText(bean.getHeight() + "cm");
                        }
                        if ("0".equals(bean.getWeight())) {
                            weightTextVew.setText("未设置");
                        } else {
                            weightTextVew.setText(bean.getWeight() + "kg");
                        }
                        ImageUtil.loadUrl($this, bean.getAvatar(), R.drawable.ic_default_head, headImageView);
                    }
                }
            }
        });

    }

}
